<?php
namespace com\mvc\core;
class Request{
	//parse url
	private $url = array("scheme" => NULL, "host" => NULL, "port" => NULL, "user" => NULL, "pass" => NULL, "path" => NULL, "query" => "", "fragment" => NULL);
	//http request method
	private $method = null;
	//_GET, _POST, _REQUEST
	private $parameters = [];

	private function requestUri()
	{
		return array_values(explode("?", $this->server("REQUEST_URI")));
	}

	public function path()
	{
		$uri = trim(rtrim($this->requestUri()[0], "/"), "/");
		//$uri = explode('/', trim($this->server('PATH_INFO'), '/'));
		$value = explode('/', filter_var($uri, FILTER_SANITIZE_URL));
		$size = count($value);
		$result = array();
		$exists = false;
		while ($size>0 && !$exists){
			$size--;
			if ($value[$size] == CONTEXT){
				$exists = true;
			}else{
				array_unshift($result,$value[$size]);
			}
		}
		return $this->url["path"] = $result;
	}

	public function query()
	{
		$uri = $this->requestUri();
		// //CLI
		// parse_str(implode('&', array_slice(filter_input_array(INPUT_GET), 1)), $query);
		//or get from request_uri
		//return $this->url["query"] = isset($uri[1]) ? $uri[1] : [];

		return $this->url["query"] = $this->server("QUERY_STRING");
	}

	public function method()
	{
		return $this->method = ($this->method === null) ? $this->server("REQUEST_METHOD") : $this->method;
	}

	public function bindingObject(&$obj,&$array){
		if (!is_object($obj)){
			$obj = new StdClass();
		}
		foreach ($array as $key=>$value){
			$method = "set".ucfirst(trim($key));
			if (method_exists($obj,$method)){
				call_user_func_array(array($obj, $method), array($value));
			}
		}
	}
	
	public function parameters($key = null)
	{
		$result = null;

		//PUT
		if($this->method() === "PUT"){
			parse_str(file_get_contents('php://input'), $result);
		}

		//_POST
		if ($this->method() === "POST") {

			if ($key !== null && null !== ($param = $this->post($key)) ) {
				$result = $param;
			}

			$result = ($result === null) ? filter_input_array(INPUT_POST) : $result;
		}

		//_GET
		if($this->method() === "GET"){
			if ($key !== null && null !== ($param = $this->get($key) )) {
				$result = explode('/', filter_var(rtrim($param, "/"), FILTER_SANITIZE_URL));
			}
			$result = ($result === null) ? filter_input_array(INPUT_GET): $result;
		}

		return $this->parameters = ($result === null) ? [] : $result;
	}

	public function env($key)
	{
		return filter_input(INPUT_ENV, $key, FILTER_SANITIZE_STRING);
	}

	public function server($key)
	{
		return filter_input(INPUT_SERVER, $key, FILTER_SANITIZE_STRING);
	}

	public function get($key)
	{
		//FILTER_SANITIZE_STRING : quotes are encoded
		return filter_input(INPUT_GET, $key, FILTER_SANITIZE_STRING);
	}

	public function post($key)
	{
		return filter_input(INPUT_POST, $key, FILTER_SANITIZE_STRING);
	}

	public function cookie($key)
	{
		return filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_NUMBER_INT);
	}

}
?>